<template>
  <div>
    <card :isCustomHeader="true">
      <template #header>
        <t-breadcrumb :maxItemWidth="'150'">
          <t-breadcrumbItem>企业管理</t-breadcrumbItem>
          <t-breadcrumbItem @click="$router.push('/business-management/user')">用户</t-breadcrumbItem>
          <t-breadcrumbItem><b>编辑用户</b></t-breadcrumbItem>
        </t-breadcrumb>
        <t-space>
          <t-button @click="save(0)" theme="default" variant="outline">取消</t-button>
          <t-button @click="save(1)">保存</t-button>
        </t-space>
      </template>
      <template>
        <div class="form">
          <t-form labelAlign="top" :data="formData" style="width: 40vw">
            <t-form-item label="用户名称" placeholder="请输入用户名称" requiredMark clearable showClearIconOnEmpty>
              <t-input v-model="formData.name"></t-input>
            </t-form-item>
            <t-form-item label="所属企业" clearable showClearIconOnEmpty requiredMark>
              <t-select v-model="formData.company" :options="companyOptions" />
            </t-form-item>
            <t-form-item label="邮箱" requiredMark placeholder="请输入企业邮箱" clearable showClearIconOnEmpty>
              <t-input v-model="formData.email">
                <template #prefix-icon>
                  <mail-icon />
                </template>
              </t-input>
            </t-form-item>
            <t-form-item label="手机号码" requiredMark clearable showClearIconOnEmpty>
              <t-input v-model="formData.phone" :maxlength="11">
                <template #prefix-icon>
                  <mobile-icon />
                </template>
              </t-input>
            </t-form-item>
            <t-form-item label="用户角色" clearable showClearIconOnEmpty>
              <t-select v-model="formData.role" :options="roleOptions" />
            </t-form-item>
            <t-form-item label="账户状态" clearable showClearIconOnEmpty>
              <t-radio-group v-model="formData.status">
                <t-radio value="1">使用中</t-radio>
                <t-radio value="2">已禁用</t-radio>
              </t-radio-group>
            </t-form-item>
            <t-form-item label="备注" clearable showClearIconOnEmpty>
              <t-textarea v-model="formData.remark" placeholder="请输入备注内容" />
            </t-form-item>
          </t-form>
        </div>
      </template>
    </card>
  </div>
</template>

<script>
import Card from '@/components/Card/index.vue';
import { MailIcon, MobileIcon } from 'tdesign-icons-vue';
import { addUser, getUserInfoById } from '@/service/business-management/users/index';
import { getEnterpriseInfo } from '@/service/business-management/business-info';
import { getAllRole } from '@/service/business-management/role/index';

const INITIAL_DATA = {
  name: '',
  company: '',
  email: '',
  phone: '',
  role: null,
  status: '',
  remark: '',
};
export default {
  components: {
    Card,
    MailIcon,
    MobileIcon,
  },
  data() {
    return {
      formData: { ...INITIAL_DATA },
      companyOptions: [],
      roleOptions: [],
    };
  },
  computed: {
    id() {
      return this.$route.query;
    },
  },
  mounted() {
    this.getAllCompany();
    this.getAllRole();
    this.getinfo();
  },
  methods: {
    async getinfo() {
      const res = await getUserInfoById(this.id);
      this.formData.name = res.name;
      this.formData.company = res.sysOrgId;
      this.formData.email = res.email;
      this.formData.phone = res.mobile;
      this.formData.role = res.sysRoleId * 1;
      this.formData.status = `${res.status}`;
      this.formData.remark = res.comment;
    },
    // 保存
    async save(val) {
      // todo
      if (val) {
        const { name, company, email, phone, role, status, remark } = this.formData;
        if (!name || !company || !phone || !email) {
          this.$message.warning('填写');
          return;
        }
        if (!this.testEmail() || !this.testPhone()) return;
        const sysUser = {
          name,
          sysOrgId: company,
          sysRoleId: role,
          status,
          comment: remark,
          email,
          mobile: phone,
          ...this.id,
        };
        const res = await addUser(sysUser);
        if (res?.code === 200) {
          this.$message.success('保存成功');
          this.$router.replace('/business-management/user');
        }
      } else {
        this.$router.replace('/business-management/user');
      }
    },
    // 账号密码登录时 判断手机号或者邮箱是否正确
    // 手机快捷登录时 判断手机号是否正确
    testEmail() {
      const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (email.test(this.formData.email) && !this.isBusinessEmail(this.formData.email)) return true;
      this.$message.error('请输入正确的企业邮箱');
      return false;
    },
    testPhone() {
      const phoneNumber = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      if (!phoneNumber.test(this.formData.phone)) {
        this.$message.error('手机号格式不正确');
        return false;
      }
      return true;
    },
    // 是否是企业邮箱
    isBusinessEmail(email) {
      const usualEmail = ['163.com', '126.com', 'qq.com', 'gmail.com', 'yeah.com', 'sina.com', 'hotmail.com'];
      const newEmail = email.slice(email.length - 11, email.length);
      return usualEmail.some((item) => {
        if (newEmail.indexOf(item) >= 0) {
          return item;
        }
        return false;
      });
    },
    // 获取所以企业信息
    async getAllCompany() {
      const res = await getEnterpriseInfo();
      this.companyOptions = res.data.map((item) => ({
        label: item.name,
        value: item.id,
      }));
    },
    // 获取所以角色权限信息
    async getAllRole() {
      const res = await getAllRole();
      this.roleOptions = res.data.map((item) => ({
        label: item.name,
        value: item.id,
      }));
    },
  },
};
</script>

<style lang="less" scoped>
.form {
  display: flex;
  justify-content: center;
  // height: 77vh;
  height: 100%;
  padding-bottom: 100px;
}
</style>
